package com.mujin.keji.collectionsystem.module.main.views;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.jaeger.library.StatusBarUtil;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.module.login.syncData.SyncDataThread;
import com.mujin.keji.collectionsystem.module.login.views.LoginActivity;
import com.mujin.keji.collectionsystem.module.login.views.SplashActivity;
import com.mujin.keji.collectionsystem.module.main.adapter.CommonViewPagerAdapter;
import com.mujin.keji.collectionsystem.module.main.adapter.MainTapPagerAdapter;
import com.mujin.keji.collectionsystem.module.main.viewmodel.MainViewModel;
import com.mujin.keji.collectionsystem.module.main.vo.ErrorVo;
import com.mujin.keji.collectionsystem.utils.DateUtil;
import com.mujin.keji.collectionsystem.utils.FileUtil;
import com.mujin.keji.collectionsystem.utils.SPUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.widget.NoScrollViewPager;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 主页面Activity
 *
 * @author weishixiong
 * @Time 2018-03-19
 */
public class MainActivity extends BaseActivity implements View.OnClickListener,  ViewPager.OnPageChangeListener {
    private NoScrollViewPager viewPager;
    private RelativeLayout rlLeftTap;
    private ImageView ivLeftTap;
    private TextView tvLeftTap;

    private RelativeLayout rlRightTap;
    private ImageView ivRightTap;
    private TextView tvRightTap;

    private List<Fragment> mFragmentList;
    private LeftFragment mLeftFragment;

    private RightFragment mRightFragment;
    private CommonViewPagerAdapter mMainTapPagerAdapter;



    @Override
    protected void createViewModel() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
//        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        CcsApplication.clearSpecifyActivities(new Class[]{SplashActivity.class});

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);
    }
    private String errorInfoUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "aaerrors" + "/";
    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void initView() {
        viewPager = (NoScrollViewPager) findViewById(R.id.viewPager);
        rlLeftTap = (RelativeLayout) findViewById(R.id.rl_left_tap);
        ivLeftTap = (ImageView) findViewById(R.id.iv_left_tap);
        tvLeftTap = (TextView) findViewById(R.id.tv_left_tap);
        rlRightTap = (RelativeLayout) findViewById(R.id.rl_right_tap);
        ivRightTap = (ImageView) findViewById(R.id.iv_right_tap);
        tvRightTap = (TextView) findViewById(R.id.tv_right_tap);
        viewPager.setOffscreenPageLimit(2);
    }



    @Override
    public void initData() {
        File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "aaerrors");
        if(!file.exists()){
            file.mkdir();
        }

        mFragmentList = new ArrayList<>();
        mLeftFragment = new LeftFragment();
        mRightFragment = new RightFragment();
        mFragmentList.add(mLeftFragment);
        mFragmentList.add(mRightFragment);

        mMainTapPagerAdapter = new CommonViewPagerAdapter(getSupportFragmentManager(), mFragmentList);
        viewPager.setAdapter(mMainTapPagerAdapter);
        String session = SPUtil.getData(Constant.SP.SP,"session",String.class,null);
        String userName = SPUtil.getData(Constant.SP.SP,Constant.SP.USER,String.class,null);
        String needSys = getIntent().getStringExtra("needSys");
        if(!TextUtils.isEmpty(session)&&!TextUtils.isEmpty(userName)&&!TextUtils.isEmpty(needSys)){
            Toast.makeText(MainActivity.this,"正在同步数据，请稍候...",Toast.LENGTH_LONG).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getLoadingDialog().showDialog();

                    Log.e(TAG, "initData: 正在同步数据，请稍候..." );
                    SyncDataThread syncDataThread = new SyncDataThread(MainActivity.this, session, userName, MainActivity.this);
                    syncDataThread.start();
                }
            },1000);

        }


    }
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            getLoadingDialog().dismiss();
            if(msg.what==3001){
                Toast.makeText(MainActivity.this,"同步完成",Toast.LENGTH_LONG).show();
            }
            else{

                Toast.makeText(MainActivity.this,(String) msg.obj,Toast.LENGTH_LONG).show();

            }
        }
    };

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }


    @Override
    public void initListener() {
        rlLeftTap.setOnClickListener(this);

        rlRightTap.setOnClickListener(this);
        viewPager.addOnPageChangeListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_left_tap:
                viewPager.setCurrentItem(0);
                break;
            case R.id.rl_right_tap:
                viewPager.setCurrentItem(1);
                break;
        }
    }


    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); //调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    /**
     * 退出应用程序
     */
    private void exitBy2Click() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true; // 准备退出
            ToastUtils.showToast("再按一次退出程序");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {

        Log.e(TAG, "onPageSelected: "+position );
        switch (position) {
            case 0:
                tvLeftTap.setTextColor(getResources().getColor(R.color.color_tap_select));
                tvRightTap.setTextColor(getResources().getColor(R.color.color_tap_normal));
                ivLeftTap.setImageResource(R.drawable.image_left_selected);
                ivRightTap.setImageResource(R.drawable.image_right_normal);
                StatusBarUtil.setColor(this, getResources().getColor(R.color.color_transt), 0);
                break;


            case 1:
                tvLeftTap.setTextColor(getResources().getColor(R.color.color_tap_normal));
                tvRightTap.setTextColor(getResources().getColor(R.color.color_tap_select));
                ivLeftTap.setImageResource(R.drawable.image_left_normal);
                ivRightTap.setImageResource(R.drawable.image_right_selected);
                StatusBarUtil.setColor(this, getResources().getColor(R.color.color_main_title), 0);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
